//########################################################################
//## (C) by Edwin Vriethoff under Microsoft Reciprocal License (Ms-RL)  ##
//## See http://www.codeplex.com/SPUserPoll/license for full license    ##
//##                                                                    ##
//## http://edwin.vriethoff.net http://www.codeplex.com/SPUserPoll/     ##
//########################################################################

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;

namespace SPUserPoll.Data.Components
{
    /// <summary>
    /// Code library to access the Admin list.
    /// </summary>
    public class AdminList
    {
        const string c_AdminList = "Available SPUserPolls";
        const string c_PollRegistrionQuery = "<Where><Eq><FieldRef Name='PollID' /><Value Type='Text'>{0}</Value></Eq></Where>";
        const string c_GetPollID = "<Where><Eq><FieldRef Name='Title' /><Value Type='Text'>{0}</Value></Eq></Where>";

        /// <summary>
        /// Get the pollID based on a foldername in the answer or response list
        /// </summary>
        /// <param name="pollFolderName"></param>
        /// <param name="web"></param>
        /// <returns></returns>
        public static string GetPollID(string pollFolderName, SPWeb web)
        {
            AdminList getAdminList = new AdminList();
            SPList adminList = null;

            if (web != null)
            {
                adminList = getAdminList.GetList(web);
            }
            else
            {
                adminList = getAdminList.GetList();
            }
            

            //Create the lookup query
            string pollQuery = string.Format(c_GetPollID, pollFolderName);
            SPQuery query = new SPQuery();
            query.Query = pollQuery;

            //query the list
            if (adminList.GetItems(query).Count > 0)
            {
                try
                {
                    return adminList.GetItems(query)[0]["PollID"].ToString();
                }
                catch
                {
                    //no items found
                    return "";
                }
            }
            else
            {
                //no items found
                return "";
            }

        }

        /// <summary>
        /// Gets the poll title of a pollID
        /// </summary>
        /// <param name="pollID"></param>
        /// <returns></returns>
        public static string GetPollTitle(string pollID)
        {
            AdminList getAdminList = new AdminList();
            SPList adminList = getAdminList.GetList();

            //Create the lookup query
            string pollQuery = string.Format(c_PollRegistrionQuery, pollID);
            SPQuery query = new SPQuery();
            query.Query = pollQuery;

            //query the list
            if (adminList.GetItems(query).Count > 0)
            {
                try
                {
                    return adminList.GetItems(query)[0]["Title"].ToString();
                }
                catch
                {
                    //title has not been set
                    return "";
                }
            }
            else
            {
                return "";
            }
        }

        /// <summary>
        /// Create a new administration list
        /// </summary>
        /// <param name="createAtWeb"></param>
        /// <returns></returns>
        public SPList CreateList(SPWeb createAtWeb)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                //open the required poll list
                using (SPWeb web = new SPSite(createAtWeb.Url).OpenWeb())
                {
                    try
                    {
                        web.AllowUnsafeUpdates = true;
                        //create the basic list
                        Guid newListGuid = web.Lists.Add(c_AdminList, "Manage all created SPUserPolls in this site collection", SPListTemplateType.GenericList);
                        SPList alterList = web.Lists[newListGuid];

                        //add additional columns to it
                        alterList.Fields.Add("PollID", SPFieldType.Text, false);
                        alterList.Fields.Add("Question", SPFieldType.Text, false);
                        alterList.Fields.Add("Location", SPFieldType.Text, false);
                        alterList.Fields.Add("View", SPFieldType.URL, false);
                        alterList.Fields.Add("Published", SPFieldType.Boolean, false);

                        //apply updates
                        alterList.Update();

                        //set view
                        SPView defaultView = alterList.DefaultView;
                        defaultView.ViewFields.DeleteAll();
                        defaultView.ViewFields.Add("LinkTitle");
                        defaultView.ViewFields.Add("PollID");
                        defaultView.ViewFields.Add("Question");
                        defaultView.ViewFields.Add("Location");
                        defaultView.ViewFields.Add("Published");
                        defaultView.ViewFields.Add("View");
                        defaultView.Query = @"<OrderBy><FieldRef Name='Location' /></OrderBy>";
                        defaultView.Update();
                    }
                    finally
                    {
                        web.AllowUnsafeUpdates = false;
                    }
                }
            });
            
            //return the list
            return GetList();
        }

        /// <summary>
        /// Update the publication state of the poll
        /// </summary>
        /// <param name="pollID"></param>
        /// <param name="published"></param>
        public void UpdatePollPublicationSate(string pollID, bool published)
        {
            SPList adminList = GetList();

            //Create the lookup query
            string pollQuery = string.Format(c_PollRegistrionQuery, pollID);
            SPQuery query = new SPQuery();
            query.Query = pollQuery;

            SPListItem pollItem = null;

            //query the list
            if (adminList.GetItems(query).Count > 0)
            {
                //the item exist and we expect 1 item on this id
                pollItem = adminList.GetItems(query)[0];
                pollItem["Published"] = published;
                pollItem.Update();
            }
        }

        /// <summary>
        /// Add or update the poll registration in the admin list
        /// </summary>
        /// <param name="pollID"></param>
        /// <param name="pollTitle"></param>
        /// <param name="pollQuestion"></param>
        /// <param name="siteName"></param>
        /// <param name="published"></param>
        /// <param name="pageUrl"></param>
        public void AddOrUpdatePollRegistration(string pollID, string pollTitle, string pollQuestion, string siteName, bool published, string pageUrl)
        {
            SPList adminList = GetList();

            //Create the lookup query
            string pollQuery = string.Format(c_PollRegistrionQuery, pollID);
            SPQuery query = new SPQuery();
            query.Query = pollQuery;

            SPListItem pollItem = null;

            //query the list
            if (adminList.GetItems(query).Count > 0)
            {
                //the item exist and we expect 1 item on this id
                pollItem = adminList.GetItems(query)[0];                
            }
            else
            {
                //create the item
                pollItem = adminList.Items.Add();
            }

            pollItem["Title"] = pollTitle;
            pollItem["PollID"] = pollID;
            pollItem["Question"] = pollQuestion;
            pollItem["Location"] = siteName;
            pollItem["Published"] = published;

            SPFieldUrlValue pollLocation = new SPFieldUrlValue();
            pollLocation.Url = pageUrl;
            pollLocation.Description = "View poll";
            pollItem["View"] = pollLocation;
            
            pollItem.Update();

        }

        /// <summary>
        /// Get the list
        /// </summary>
        /// <returns></returns>
        public SPList GetList()
        {
            //we recreate the siteobject because sharepoint does not see newly created lists in the already openend site
            using (SPWeb web = new SPSite(SPContext.Current.Web.Site.RootWeb.Url).OpenWeb())
            {
                try
                {
                    return web.Lists[c_AdminList];
                }
                catch (ArgumentException)
                {
                    //recreate the adminlist
                    return CreateList(web);
                }
            }
        }

        /// <summary>
        /// Get the list from the specified web (used by Eventhandler)
        /// </summary>
        /// <param name="fromWeb"></param>
        /// <returns></returns>
        private SPList GetList(SPWeb fromWeb)
        {
            //we recreate the siteobject because sharepoint does not see newly created lists in the already openend site
            using (SPWeb web = new SPSite(fromWeb.Site.RootWeb.Url).OpenWeb())
            {
                try
                {
                    return web.Lists[c_AdminList];
                }
                catch (ArgumentException)
                {
                    //recreate the adminlist
                    return CreateList(web);
                }
            }
        }


    }
}
